package controller;

import java.util.ArrayList;
import java.util.List;

import model.Card;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import service.Filter;

@Controller("homeController")
public class HomeController {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public HomeController() {
		// TODO Auto-generated constructor stub
	}
	@RequestMapping("/cardInfo.do")
	public ModelAndView displayCardInfo(Model model, @RequestParam(required = true) int cardId  ){
		
		ModelAndView mav = new ModelAndView();
		Card card = Card.getById(cardId, sessionFactory.openSession());
		mav.getModelMap().put("card", card);
		mav.getModel().put("controller", "this is homeController speaking");
		mav.setViewName("cardInfo");
		return mav;
	}
	@RequestMapping("/home.do")
	public ModelAndView displayHome(Model model){
		ModelAndView mav = new ModelAndView();
		List<Card> cards = Card.getAll(sessionFactory.openSession());
		mav.getModelMap().put("cards", cards);
		mav.setViewName("home");
		return mav;
	}
	@RequestMapping("/search.do")
	public ModelAndView search(Model model, @RequestParam(required = true) String query,
			@RequestParam(required = false) Integer page,
			@RequestParam(required = false) String filter){
		if(page == null || page < 0) page = 0;
		ModelAndView mav = new ModelAndView();
		List<Card> cards = Card.getAllVersions(query,sessionFactory.openSession());
		Filter f = null;
		if(filter != null){
			mav.getModelMap().put("filter", filter);
			try {
				f = new Filter(filter);
				cards = Card.getAllVersions(query, sessionFactory.openSession(), f);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (cards.size() > 25) {
			cards = getPage(cards,page);
		}
		mav.getModelMap().put("cards", cards);
		mav.getModelMap().put("searchResults", cards.size());
		mav.getModelMap().put("query", query);
		mav.getModelMap().put("page", page);
		mav.setViewName("home");
		
		return mav;
	}
	private List<Card> filter(List<Card> cards, String filter) {
		
		return null;
	}
	private List<Card> getPage(List<Card> cards, int page) {
		List<Card> result = new ArrayList<Card>(25);
		for(int i = 0; i < 25; i++){
			if (25*page + i  < cards.size()) {
				result.add(cards.get(25 * page + i));
			}
		}
		return result;
	}

}
